package lang.var.atom;

import lang.var.Position;

public class Atomizer {
  private final Position position = new Position();
  private AtomReciever reciever;
  
  private abstract class MyAtom extends Atom {
    final Position startedAt;
    
    @SuppressWarnings("unused")
    MyAtom(Position startedAt) {
      this.startedAt = startedAt;
    }
    
    MyAtom() {
      startedAt = position.copy();
    }
    
    @Override
    public Position position() {
      return position;
    }
  }
  
  public void setReciever(AtomReciever reciever) {
    this.reciever = reciever;
  }
  
  public void append(char[] buffer, int size) {
    for (int i = 0; i < size; i++) {
      appendChar( buffer[i] );
    }
  }
  
  public void finish() {
    
  }
  
  private InState inState = InState.SPACE;
  @SuppressWarnings("unused")
  private String content;
  @SuppressWarnings("unused")
  private char strOpenChar;
  
  private void appendChar(char c) {
    switch (inState) {
    case SPACE:
      if (Character.isWhitespace( c )) {
        position.addChars( 1 );
        return;
      }
      if (c == '\r') return;
      if (c == '\n') {
        reciever.recieve( newLine() );
        position.newLine();
        return;
      }
      
      if (Character.isDigit( c )) {
        content = "" + c;
        inState = InState.NUMBER;
        position.addChars( 1 );
        return;
      }
      
      if (Character.isLetter( c )) {
        content = "" + c;
        inState = InState.STRING;
        position.addChars( 1 );
        return;
      }
      
      error( "Unknown char: " + c );
      return;
    default:
      return;
    }
  }
  
  private void error(String message) {
    // TODO Auto-generated method stub
    
  }
  
  private Atom newLine() {
    return new MyAtom() {
      @Override
      public AtomType type() {
        return AtomType.NEW_LINE;
      }
      
      @Override
      public String content() {
        return "\n";
      }
      
      @Override
      public int charCount() {
        return 1;
      }
    };
  }
}
